#!/bin/bash
##############################################################
source ./pkgutils.sh || exit 1
PKG_NAME=$(pkgname); if (( $? != 0)); then exit 2; fi
PKG_VERSION=$(pkgversion); if (( $? != 0)); then exit 3; fi
if [[ $(whoami) != "root" ]]; then
	echo "Please log in as user root...";
	exit 4;
fi
mkdir -pv ./tmp && cd ./tmp || exit 5;
echo "setup of $PKG_NAME $PKG_VERSION";
##############################################################
# do setup tasks (location: /usr/pkg/$PKG_NAME/$PKG_VERSION/tmp)
[ -d /srv/pgsql/data ] || {
    install -v -dm700 /srv/pgsql/data && \
    echo "/srv/pgsql/data" >> /usr/pkg/installed.db/${PKG_NAME}_${PKG_VERSION}_pkg.files;
} && \
[ -d /run/postgresql ] || {
    install -v -dm755 /run/postgresql && \
    echo "/run/postgresql" >> /usr/pkg/installed.db/${PKG_NAME}_${PKG_VERSION}_pkg.files;
} && \
[[ $(cat /etc/group | grep '^postgres:') != "" ]] || groupadd -g 41 postgres && \
[[ $(cat /etc/passwd | grep '^postgres:') != "" ]] || useradd -c "PostgreSQL Server" -g postgres -d /srv/pgsql/data \
        -u 41 postgres && \
chown -Rv postgres:postgres /srv/pgsql /run/postgresql && \
[[ $(ls /srv/pgsql/data/) != "" ]] || su - postgres -c '/usr/bin/initdb -D /srv/pgsql/data' && \
su - postgres -c '/usr/bin/postmaster -D /srv/pgsql/data > /srv/pgsql/data/logfile 2>&1 &' && \
su - postgres -c '/usr/bin/createdb test' && \
echo "create table t1 ( name varchar(20), state_province varchar(20) );" \
    | (su - postgres -c '/usr/bin/psql test ') && \
echo "insert into t1 values ('Billy', 'NewYork');" \
    | (su - postgres -c '/usr/bin/psql test ') && \
echo "insert into t1 values ('Evanidus', 'Quebec');" \
    | (su - postgres -c '/usr/bin/psql test ') && \
echo "insert into t1 values ('Jesse', 'Ontario');" \
    | (su - postgres -c '/usr/bin/psql test ') && \
echo "select * from t1;" | (su - postgres -c '/usr/bin/psql test')


# hint: write all file modifications/copy/mv/ln into: /usr/pkg/installed.db/${PKG_NAME}_${PKG_VERSION}_pkg.files
##############################################################
ERR=$?;
if (($ERR != 0)); then
    errcho "Aborted package setup with code $ERR";
    exit 6;
fi
